<?php
namespace app\appletsapi\controller;

use app\common\model\Order;
use app\common\model\Payments;
use app\common\model\User;
use Firebase\JWT\JWT as JWTUtil;
use think\facade\Config;
use think\facade\Log;
use wxzhifu\example\WxPayConfig;
use wxzhifu\lib\WxPayApi;
use wxzhifu\lib\WxPayOrderQuery;
use think\facade\Env;

class ApiNotify extends Base
{

    /**
     * @route('applets/notify')
     */
    public function notify()
    {
        $notify = $this->NotifyProcess();
        if($notify != false){
            $paymentsinfo = $notify['paymentsinfo'];
            $orderModel = new \app\common\model\Order();
            Log::init([
                'path' => Env::get('runtime_path')."offlinepaylog/",
            ]);
            switch($paymentsinfo['payments_type']){
                case 'offline':
                    $rs = $orderModel->offlinepaySuccess($notify);
                    if($rs === false){
                        Log::record($orderModel->getError(),"error");
                    }
                    break;
                default:
                    Log::record('支付记录类型错误','error');
                    break;
            }
            if($rs === false){
                Log::record($orderModel->getError(),"error");
                $this->recordlog("订单失败",'error');
                return "<xml>
                      <return_code><![CDATA[FAIL]]></return_code>
                      <return_msg><![CDATA[]]></return_msg>
                      </xml>";
            }
            $this->recordlog("订单成功",'success');
            return "<xml>
                  <return_code><![CDATA[SUCCESS]]></return_code>
                  <return_msg><![CDATA]></return_msg>
                  </xml>";
        }
        $this->recordlog("订单失败",'error');
        return "<xml>
              <return_code><![CDATA[FAIL]]></return_code>
              <return_msg><![CDATA[]]></return_msg>
              </xml>";

    }

    public function NotifyProcess()
    {
        //获取返回的xml
        $testxml = file_get_contents("php://input");
        $this->recordlog("--------begin xml--------".$testxml."--------end xml--------",'info');
//        var_dump($testxml);
        //将xml转化为json格式
        $jsonxml = json_encode(simplexml_load_string($testxml, 'SimpleXMLElement', LIBXML_NOCDATA));
        //转成数组
        $result = json_decode($jsonxml, true);
        $this->recordlog("--------begin notify--------".print_r($result,true)."--------end notify--------",'info');
        if (!array_key_exists("transaction_id", $result)) {
            $msg = "transaction_id输入参数不正确";
            $this->recordlog($msg,'error');
            return false;
        }
        if (!array_key_exists("out_trade_no", $result)) {
            $msg = "out_trade_no输入参数不正确";
            $this->recordlog($msg,'error');
            return false;
        }
        if (!array_key_exists("openid", $result)) {
            $msg = "openid输入参数不正确";
            $this->recordlog($msg,'error');
            return false;
        }
        $attch = json_decode($result['attach'],true);
        $pay_end = isset($attch['pay_end'])?$attch['pay_end']:'1';
        //查询订单，判断订单真实性
        if (!$this->Queryorder($result["transaction_id"],$pay_end)) {
            $msg = "订单查询失败";
            $this->recordlog($msg,'error');
            return false;
        }

		$userModel = new User();
        $query_field = $pay_end == 1?"wx_openid":"applets_openid";
		$user = $userModel
			->field('user_id,invite_uid,nick_name,growth_coin,wx_openid,applets_openid')
			->where(["{$query_field}"=>$result['openid']])
			->find();
		if (empty($user)) {
			$msg = "不存在的用户";
			$this->recordlog($msg,'error');
			return false;
		}
		$user = $user->toArray();

		$OrderModel = new Order();
		$where = [
//			['pay.user_id','=',$user['user_id']],
			['pay.order_nos','=',$result['out_trade_no']],
		];
		$payments = $OrderModel->alias('o')->field('o.order_id,o.shop_id,o.orderno,pay.*,p.sale_id,p.profit,p.shop_name')->where($where)->leftJoin([
			['ddt_payments pay','pay.payments_id = o.payments_id'],
			['ddt_shops p','o.shop_id = p.shop_id'],
		])->find();
		if (empty($payments)) {
			$msg = "无下单购物记录";
			$this->recordlog($msg,'error');
			return false;
		}
		$paymentsinfo = $payments->toArray();
		//查询购买记录
		$this->recordlog($paymentsinfo,'info');
		if ($paymentsinfo['status'] != '1') {
			$msg = "购买记录状态异常";
			$this->recordlog($msg,'error');
			return false;
		}

		$total_fee = $result['total_fee'];//bcdiv($data['total_fee'], 100, 2);
		if ($total_fee != calculate([$paymentsinfo['amount'],100],'*',0)) {
			$msg = "订单金额错误";
			$this->recordlog($msg,'error');
			return false;
		}

		$data = [
			'back_info' => json_encode($result),
			'paymentsinfo' => $paymentsinfo,
			'transaction_id' => $result["transaction_id"],
			'user' => $user,
            'pay_end' => $pay_end,
		];
        return $data;
    }

    private function recordlog($msg,$ltype){
        Log::init([
            'path' => Env::get('runtime_path')."offlinepaylog/",
        ]);
        Log::record($msg,$ltype);
    }

    //查询订单
    public function Queryorder($transaction_id,$pay_end = 1)
    {
        if($pay_end == 1){
            $wxconfig = Config::pull('weixin_applet');
        } else {
            $wxconfig = Config::pull('weixin');
        }
        $config = new WxPayConfig();
        $config->appid = $wxconfig['AppID'];
        $config->secret = $wxconfig['AppSecret'];
        $config->mchid = $wxconfig['MchId'];
        $config->key = $wxconfig['MchKey'];
        $input = new WxPayOrderQuery();
        $input->SetTransaction_id($transaction_id);
        $result = WxPayApi::orderQuery($config,$input);
        if (array_key_exists("return_code", $result)
            && array_key_exists("result_code", $result)
            && $result["return_code"] == "SUCCESS"
            && $result["result_code"] == "SUCCESS"
        ) {
            return true;
        }
        return false;
    }
}
